/////////////////////////////////////////////////////////////////////////

package sheep.view;

/////////////////////////////////////////////////////////////////////////
import java.awt.event.ActionEvent;
import java.io.File;
import sheep.model.Project;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;

import javax.swing.JSeparator;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import org.jdesktop.swingx.JXCollapsiblePane;
import org.jdesktop.swingx.JXCollapsiblePane.Orientation;
import org.jdesktop.swingx.VerticalLayout;
import sheep.view.transitions.TransitionTarget;
import sheep.view.transitions.ScreenTransition;

//import org.progx.twinkle.ui.PictureViewer;

/////////////////////////////////////////////////////////////////////////
import sheep.controller.Workspace;
import sheep.model.Task;
import sheep.view.Component.CoolBar;
import sheep.view.Component.CoolButton;
import sheep.view.graphics2d.ShadowFactory;
import sheep.view.utils.swingx.DropShadowPanel;

import javax.swing.filechooser.*;
import java.io.File;
import sheep.model.Task.GraphMode;
import sheep.utils.fileio.FileUtils;
import sheep.utils.fileio.PDFExporter;
import sheep.utils.fileio.PrintUtilities;
import sheep.view.Component.ImageChooser.Utils;
import sheep.view.VisualProjectPanel.GrpaheScreenType;

class TransitionPanel extends JPanel {
  
  /////////////////////////////////////////////////////////////////////////
  
  // duree des transitons
  private static final int TRANSITION_TIME_IN_MILLIS = 500;
 
  // Flag pour connaitre le panel affich"
  private enum ScreenType { MAIN,PROJECT_MAIN,AGENDA, USER, GRAPH_DESIGNER, GRAPH_EDITOR, GANTT_EDITOR }
  // Valeur des ecrans courant et precedent
  private ScreenType currentScreen;
  private ScreenType oldScreen;   
      
  // Panel conteneur general    
  private final JPanel content;  
       
  // Panel de l'application que l'on ajoutera a content    
  private final MainPanel mainPanel;    
  private final ProjectPanel projectPanel;
  private ProjectSelectPanel projectSelectPanel;
  private final ProjectNewPanel projectEditPanel;
  private UserPanel userPanel;    
  //private PictureViewer slideshowPanel;    
  private final VisualProjectPanel visualProjectPanel;    
  //private final AgendaWeekViewer agendaWeekViewer;    
  private final AgendaViewer agendaViewer;
  //private final AgendaDayViewer agendaDayViewer;
        
  // Toolbar    
  private JComponent mainToolBar;
    
  // Pour creer le fond de la zone retractable    
  private ContentPanel jxToolBarPanel;   
  // Panel retractable pour la toolbar    
  private JXCollapsiblePane collapser;    
  // Gestionnaire de transitions utilisee    
  private final ScreenTransition screenTransition; 
  private Workspace workSpace;    
  /////////////////////////////////////////////////////////////////////////
    
    
  // Panel gerant les transition
    
  TransitionPanel(final NavigationHeader navigationHeader, Workspace workSpace) {
           
    super(new BorderLayout());
    this.workSpace = workSpace;
        
    // S'occupe de ce qui se passe derriere
    setOpaque(false);   
        
    // Panel de travail general      
    content = new JPanel();
    content.setLayout(new BorderLayout());        
    content.setOpaque(false);
        
    // Création des panells de l'application       
    mainPanel = new MainPanel(workSpace);      
    projectPanel = new ProjectPanel(workSpace);      
    userPanel = new UserPanel(workSpace);            
    content.add(mainPanel, BorderLayout.CENTER);        
    visualProjectPanel = new VisualProjectPanel(workSpace);        
    agendaViewer = new AgendaViewer(workSpace);
    projectEditPanel = new ProjectNewPanel(workSpace);
    projectSelectPanel = new ProjectSelectPanel(workSpace);
    //ToolBar optionnel        
    mainToolBar = createMainToolBar();      
    
    // Création d'un panel dégradé comme le fond    
    jxToolBarPanel = new ContentPanel();    
    jxToolBarPanel.setBorder(new EmptyBorder(0,0,0,0));    
    jxToolBarPanel.setLayout(new BorderLayout());
    jxToolBarPanel.add(mainToolBar, BorderLayout.EAST);    
    
    // Panel dynamiquement retractable ou l'on ajoute la toolbar
    // et le panel dégradé en fond   
    collapser = new JXCollapsiblePane();  
    collapser.setContentPane(jxToolBarPanel);
    collapser.setBorder(new EmptyBorder(0,0,0,0));
    collapser.setLayout(new BorderLayout()); 
    collapser.setOrientation(Orientation.HORIZONTAL);
    collapser.setCollapsed(true);     
    
    // On ajoute la barre de  navig., la toolbar retractable,et 
    // le panel general
    add(navigationHeader, BorderLayout.NORTH); 
    add(content, BorderLayout.CENTER);
    add(collapser, BorderLayout.EAST);
    // Par defaut on est sur l'ecran principal
    currentScreen = ScreenType.MAIN;
    // Lance l'animation d'affichage du premier ecran
    screenTransition = new ScreenTransition(content, 
            new ContentTransitionTarget());
    
  }
    
  // On veut que tous soit affiche
  void setContentVisible(boolean visible) {
     content.setVisible(visible);
  }
    
  // Affiche la panel principal
  void showMainPanel() {
     startTransition(ScreenType.MAIN);
  }
    
  // Affiche la panel de projet
  void showMainProjectPanel() {
     startTransition(ScreenType.PROJECT_MAIN);  
  }
    
  // Affiche la panel de projet
  void showUserPanel() {
     startTransition(ScreenType.USER);  
  }
  
  // Affiche la panel de projet  
  void showAgendaPanel() {
     startTransition(ScreenType.AGENDA);  
  }
     
  void showVisualProjectPanel() {
    this.workSpace.getCurrentProject().getGraph().criticalPath(true);
    visualProjectPanel.refreshGraph();
     startTransition(ScreenType.GRAPH_DESIGNER);
     visualProjectPanel.showGraphe();
     
  }
  
   void showEditPanel() {
     this.workSpace.getCurrentProject().getGraph().criticalPath(true);
   if (visualProjectPanel.getCurrentScreen()==GrpaheScreenType.GRAPH){
    visualProjectPanel.refreshGraph();
     startTransition(ScreenType.GRAPH_DESIGNER);
     visualProjectPanel.showGraphe();
   }else{
     visualProjectPanel.refreshGraph();
     startTransition(ScreenType.GANTT_EDITOR);
     visualProjectPanel.showGANTT();
   }
  }  
   
  void showProjectEditPanel() {
    this.workSpace.getCurrentProject().getGraph().criticalPath(true);
    projectEditPanel.refresh();
     startTransition(ScreenType.GRAPH_EDITOR);
  }  
  
  void showGanttPanel() {
    this.workSpace.getCurrentProject().getGraph().criticalPath(true);
    visualProjectPanel.refreshGraph();
     startTransition(ScreenType.GANTT_EDITOR);
     visualProjectPanel.showGANTT();
 
  }  
  
  
  // Lance la trnsition vers le nouveau panel
  private void startTransition(ScreenType newScreen) {
     if (newScreen != currentScreen || newScreen== ScreenType.GRAPH_EDITOR) {
         oldScreen = currentScreen;
         currentScreen = newScreen;
         screenTransition.startTransition(TRANSITION_TIME_IN_MILLIS);
     }
  }
 
  public void refreshGraph(){
     if (this.workSpace.getCurrentTask()!=null){
       projectEditPanel.refresh();
        visualProjectPanel.refreshGraph();        
        repaint();
     }
   }
  
   public void refreshAfterLoad() {
       userPanel.refresh();
       projectSelectPanel.refresh();
       visualProjectPanel.refreshGraph();
       projectEditPanel.refresh();
       userPanel.refresh();
   }
      
  /////////////////////////////////////////////////////////////////////////

  // Getters des panels
  MainPanel       getMainPanel()    {return mainPanel;}   
  ProjectPanel    getMainProjectPanel() {return projectPanel;} 
  UserPanel    getUserPanel() {return userPanel;} 
  //PictureViewer   getSlideshowPanel()   {return slideshowPanel;} 
  VisualProjectPanel getTripPlannerPanel() {return visualProjectPanel;}
  //AgendaWeekViewer getAgendaWeekViewerPanel() {return agendaWeekViewer;}
  //AgendaDayViewer getAgendaDayViewerPanel() {return agendaDayViewer;}
  AgendaViewer getAgendaPanel() {return agendaViewer;}
  JXCollapsiblePane getToolBarCollapser() {return collapser;}
   
    
  /////////////////////////////////////////////////////////////////////////

  private static class ShowMainProjecttHandler implements ActionListener {
     public void actionPerformed(ActionEvent e) {TransitionManager.showMainPoject();}}
   
  private static class ShowUserHandler implements ActionListener {
     public void actionPerformed(ActionEvent e) {TransitionManager.showUser();}}

  private static class ShowAgendaHandler implements ActionListener {
     public void actionPerformed(ActionEvent e) {TransitionManager.showAgenda();}}       
   
  private static class ExitHandler implements ActionListener {
     public void actionPerformed(ActionEvent e) {System.exit(0);}}
      
  private static class ShowAccueilHandler implements ActionListener {
     public void actionPerformed(ActionEvent e) {TransitionManager.showMainScreen();}}

  private static class printHandler implements ActionListener {
     public void actionPerformed(ActionEvent e) {
     }}

  /////////////////////////////////////////////////////////////////////////
     
    
  private JComponent createMainToolBar() {
     JToolBar mainTempToolBar =  new CoolBar(true);
     mainTempToolBar.setName("toolbar");
     mainTempToolBar.setFloatable(false);
     mainTempToolBar.setOrientation(JToolBar.VERTICAL);
     mainTempToolBar.setOpaque(false);
     mainTempToolBar.setVisible(true);
     mainTempToolBar.setBackground(Color.YELLOW);
      
     VerticalLayout verticalLayout= new VerticalLayout();
     verticalLayout.setGap(10);
     mainTempToolBar.setLayout(verticalLayout);
     JComponent retComp;
     retComp = mainTempToolBar;
        
     JLabel logo = new JLabel();
     logo.setOpaque(false);
     logo.setIcon(new ImageIcon(getClass().getResource("/resources/images/sheep_small_title.gif")));
              
     JButton getMailButton = createToolbarButton("Nouveau", "copy", 1);

     JButton saveButton = createToolbarButton("Sauver", "file", 2);
     saveButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
        
        if(workSpace.getSavePath() == null) {
          FileFilter workspaceFilter = new FileFilter(){
            public boolean accept(File f) {
               if (f.isDirectory()) {
                   return true;
               }

               String extension = Utils.getExtension(f);
               if (extension != null) {
                 if (extension.equals(FileUtils.getFileExtension()))
                     return true;
                   else
                     return false;
               }

               return false;
             }

             public String getDescription() {
               return "Fichier de sauvegarde (*."+FileUtils.getFileExtension()+")";
             }
          };
          
          JFileChooser chooser = new JFileChooser();
          //chooser.addChoosableFileFilter(workspaceFilter);
          chooser.setAcceptAllFileFilterUsed(false);
          chooser.setFileFilter(workspaceFilter);
          int returnVal = chooser.showSaveDialog(new JPanel());
          if(returnVal == JFileChooser.APPROVE_OPTION) {
            workSpace.setSavePath(chooser.getCurrentDirectory() + 
                  System.getProperties().getProperty("file.separator"));
            if(Utils.getExtension(chooser.getSelectedFile()) == null)
              workSpace.setSaveFile(chooser.getSelectedFile().getName()+"."+FileUtils.getFileExtension());
            else
              workSpace.setSaveFile(chooser.getSelectedFile().getName());

          }
        }
        workSpace.saveWorkspace();
      }
     });
     
     JButton saveAsButton = createToolbarButton("Enregistrer sous...", "file", 2);
     saveAsButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
        
        FileFilter workspaceFilter = new FileFilter(){
          public boolean accept(File f) {
             if (f.isDirectory()) {
                 return true;
             }

             String extension = Utils.getExtension(f);
             if (extension != null) {
               if (extension.equals(FileUtils.getFileExtension()))
                   return true;
                 else
                   return false;
             }

             return false;
           }

           public String getDescription() {
             return "Fichier de sauvegarde (*."+FileUtils.getFileExtension()+")";
           }
        };

        JFileChooser chooser = new JFileChooser();
        //chooser.addChoosableFileFilter(workspaceFilter);
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setFileFilter(workspaceFilter);
        int returnVal = chooser.showSaveDialog(new JPanel());
        if(returnVal == JFileChooser.APPROVE_OPTION) {
          workSpace.setSavePath(chooser.getCurrentDirectory() + 
                System.getProperties().getProperty("file.separator"));
          
          if(Utils.getExtension(chooser.getSelectedFile()) == null)
              workSpace.setSaveFile(chooser.getSelectedFile().getName()+"."+FileUtils.getFileExtension());
            else
              workSpace.setSaveFile(chooser.getSelectedFile().getName());

        }
        workSpace.saveWorkspace();
      }
     });
     
     JButton openButton = createToolbarButton("Ouvrir", "paste", 3);
     openButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
        
        FileFilter workspaceFilter = new FileFilter(){
          public boolean accept(File f) {
             if (f.isDirectory()) {
                 return true;
             }

             String extension = Utils.getExtension(f);
             if (extension != null) {
               if (extension.equals(FileUtils.getFileExtension()))
                   return true;
                 else
                   return false;
             }

             return false;
           }

           public String getDescription() {
             return "Fichier de sauvegarde (*."+FileUtils.getFileExtension()+")";
           }
        };

        JFileChooser chooser = new JFileChooser();
        //chooser.addChoosableFileFilter(workspaceFilter);
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setFileFilter(workspaceFilter);
        int returnVal = chooser.showOpenDialog(new JPanel());
        if(returnVal == JFileChooser.APPROVE_OPTION) {
          workSpace.setSavePath(chooser.getCurrentDirectory() + 
                System.getProperties().getProperty("file.separator"));
          workSpace.setSaveFile(chooser.getSelectedFile().getName());
        }
        workSpace.openWorkspace();
        //userPanel = new UserPanel(workSpace);
        userPanel.refresh();
        projectSelectPanel.refresh();
        visualProjectPanel.refreshGraph();
        projectEditPanel.refresh();
        userPanel.refresh();
        
      }
     });
     
        
     JButton addressBookButton = createToolbarButton("Exporter", "compose-mail", 1);
     addressBookButton.addActionListener(new ActionListener(){

      @Override
      public void actionPerformed(ActionEvent arg0) {
        PDFExporter exp = new PDFExporter(workSpace);
        exp.export();
      }
     
     });
     //addressBookButton.addActionListener(new ShowMainProjecttHandler());
        
     JButton replyButton = createToolbarButton("Personnel", "show-address-book", 2);
     replyButton.addActionListener(new ShowAgendaHandler());
        
     JButton replyAllButton = createToolbarButton("Agenda", "address-book", 3);
     replyAllButton.addActionListener(new ShowAgendaHandler());
        
     JButton forwardButton = createToolbarButton("Precedent", "previous", 1);    
     JButton deleteButton = createToolbarButton("Suivant", "next", 2);        
       
     JButton junkButton = createToolbarButton("Accueil", "task-create-trip", 3);
     junkButton.addActionListener(new ShowAccueilHandler());
                
     JButton printButton = createToolbarButton("Print", "print", 1);
     printButton.addActionListener(new ActionListener(){

      public void actionPerformed(ActionEvent e) {
         PrintUtilities.printComponent(workSpace.getCurrentTask().getGraphMode()== GraphMode.NORMAL ?
         workSpace.getCurrentTask().getGraph().getVv() :
         workSpace.getCurrentTask().getGraph().getAutoVv());
      }
       
     });
     
     
     JButton stopButton = createToolbarButton("Quitter", "delete", 3);
     stopButton.addActionListener(new ExitHandler());   

     mainTempToolBar.add(Box.createVerticalStrut(5));
     mainTempToolBar.add(logo);
          
     DropShadowPanel dsp = createDropShadowPanel();
     dsp.setLayout(new VerticalLayout());
     dsp.setBorder(new javax.swing.border.EmptyBorder(2, 4, 6, 4));
     dsp.add(getMailButton);
     dsp.add(saveButton);
     dsp.add(saveAsButton);
     dsp.add(openButton);         
     mainTempToolBar.add(dsp);
            
     dsp = createDropShadowPanel();
     dsp.setLayout(new VerticalLayout());
     dsp.setBorder(new javax.swing.border.EmptyBorder(2, 4, 6, 4));
     dsp.add(addressBookButton);
     dsp.add(replyButton);
     dsp.add(replyAllButton);           
     mainTempToolBar.add(dsp);
           
     /*dsp = createDropShadowPanel();
     dsp.setLayout(new VerticalLayout());
     dsp.setBorder(new javax.swing.border.EmptyBorder(2, 4, 6, 4));
     dsp.add(forwardButton);
     dsp.add(deleteButton);
     dsp.add(junkButton);
     mainTempToolBar.add(dsp);*/
            
     dsp = createDropShadowPanel();
     dsp.setLayout(new VerticalLayout());
     dsp.setBorder(new javax.swing.border.EmptyBorder(2, 4, 6, 4));
     dsp.add(printButton);
     dsp.add(stopButton);
     mainTempToolBar.add(dsp);

     return retComp;  
  }
        
  private static DropShadowPanel createDropShadowPanel() {      
    DropShadowPanel dsp = new DropShadowPanel();        
    ShadowFactory factory = new ShadowFactory(5, 0.2f, Color.BLACK);        
    dsp.setShadowFactory(factory);       
    dsp.setDistance(5);       
    dsp.setAngle(100f);        
    dsp.setLayout(new BoxLayout(dsp, BoxLayout.X_AXIS));        
    return dsp;   
  }
    
    
  private JButton createToolbarButton(String text, String icon, int type) {        
    JButton button =  new CoolButton(type) ;
    button.setIcon(new ImageIcon(getClass().getResource("/resources/icons/" + icon + "_01.png")));
    button.setText(text);
    button.setBorder(BorderFactory.createEmptyBorder(4, 12, 3, 12));
    button.setDisabledIcon(new ImageIcon(getClass().getResource("/resources/icons/" + icon + "_03.png")));
    button.setFocusPainted(false);
    button.setHorizontalTextPosition(SwingConstants.CENTER);
    button.setRolloverIcon(new ImageIcon(getClass().getResource("/resources/icons/" + icon + "_02.png")));
    button.setVerticalTextPosition(SwingConstants.BOTTOM);
    button.setRequestFocusEnabled(false);
    return button;  
  }
  
  
  /////////////////////////////////////////////////////////////////////////

  private class ContentTransitionTarget implements TransitionTarget {

  /////////////////////////////////////////////////////////////////////////

  @Override
  // Vide la zone principal
  public void resetCurrentScreen() {
     content.removeAll();
  }

  @Override
  // Ajoute le panel correspondant au flag au panel general
  public void setupNextScreen() {
     switch(currentScreen) {
        case MAIN:
             content.add(mainPanel, BorderLayout.CENTER);
             break;
        case PROJECT_MAIN:
             content.add(projectSelectPanel, BorderLayout.CENTER);
             break;   
        case AGENDA:
             content.add(agendaViewer, BorderLayout.CENTER);
             break;           
        case GRAPH_DESIGNER:
             content.add(visualProjectPanel, BorderLayout.CENTER);
             break;
        case GRAPH_EDITOR:
             content.add(projectEditPanel, BorderLayout.CENTER);
             break;
        case GANTT_EDITOR:
             content.add(visualProjectPanel, BorderLayout.CENTER);
             break;              
        case USER:
             content.add(userPanel, BorderLayout.CENTER);
             break;    
        default:
              assert false;
              break;
     }      
  }
      
  @Override
  // Si on vient du slideshow, on le detruit
  public void transitionComplete() {}
 
  }
      
  /////////////////////////////////////////////////////////////////////////

}

/////////////////////////////////////////////////////////////////////////

